package other.system.client.oa.submit;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.data.model.Campaign;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.QueryResult;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.task.FutureTask;
import org.apache.commons.lang.StringUtils;
import other.system.client.util.HCXObjectService;
import other.system.client.util.ResultBody;
import other.system.client.util.TfReturnMsgTools;

import java.util.List;
import java.util.Objects;

/**
 * @Description 提交市场活动模块
 * @Author 黎炎松
 * 2024-07-10 13:50
 */
public class SubmitCampaign extends SubmitSuper {
    private static HCXObjectService hcxObjectService = new HCXObjectService();

    private static XoqlService xoqlService = XoqlService.instance();

    private static final String LOGGER_MSG = "推送市场活动审批数据到OA ==> ";

    private static final Logger logger = LoggerFactory.getLogger();

    public static void main(String[] args) throws ApiEntityServiceException {
        SubmitCampaign submitCampaign = new SubmitCampaign();

        //submitCampaign.pushCampaignToOA(3305458769943108L);
        // 需切换测试环境进行测试，正式环境发送会导致他们的人员账号收到审批提醒
        submitCampaign.pushCampaignToOA(3450286457985629L);
    }

    /**
     * 提交市场活动数据到OA审批  campaign
     * @param
     * @return
     */
    public String pushCampaignToOA(Long campaignId) {
        try {
            logger.info(LOGGER_MSG + "处理开始: " + campaignId);

            // 获取基本信息
            String sql = "select id,campaignName,dimDepart.departName departName,demandDepartment__c.departName demandDepartmentName,entryName__c,itemNumber__c," +
                    "marketingActivity__c,activityNature__c,projectRequirements__c,projectApprovalContent__c,effectsBenefits__c,projectPlan__c,numberOfCustomers__c,total__c," +
                    "businessOpportunities__c,orderAmount__c,budgetFiling__c,exceedingBudget__c,oaApprovalId__c,oaApprovalStatus__c,attachment__c," +
                    "ownerId.LoginName__c ownerOaAccount,ownerId.personalEmail ownerOaEmail,countersignNode__c.LoginName__c oaAccount,countersignNode__c.personalEmail oaEmail " +
                    " from campaign where id = " + campaignId;
            QueryResult<JSONObject> query = xoqlService.query(sql, true);
            List<JSONObject> records = query.getRecords();
            if (records.size() <= 0) {
                logger.error(LOGGER_MSG + "获取市场活动数据异常");
                return TfReturnMsgTools.getFailResult("获取市场活动数据异常:" + query.getErrorMessage());
            }

            // 获取字段信息
            JSONObject campaign = records.get(0);
            String campaignName = campaign.getString("campaignName");
            String oaApprovalId = campaign.getString("oaApprovalId__c");
            String oaApprovalStatus = getOptionStr(campaign.getJSONArray("oaApprovalStatus__c"));
            // 如果是 作废 状态，则重新提交
            if (Objects.equals(oaApprovalStatus, "作废")) {
                oaApprovalId = "";
            }

            // 立项预算明细数据
            sql = "select id,expenseAccount__c,costDescription__c,money__c,remarks__c from budgetDetails__c where customItem1__c = " + campaignId;
            List<JSONObject> budgetDetailsList = xoqlService.query(sql, true).getRecords();

            // 拼接表单的数据
            JSONObject formObject = new JSONObject();
            formObject.put("fd_3ba5f6e127b028", campaign.getString("departName")); // 立项部门
            formObject.put("fd_3ba5f7055c0f40", campaign.getString("demandDepartmentName")); // 需求部门
            formObject.put("fd_374247dd65d242", campaign.getString("entryName__c")); // 项目名称
            formObject.put("fd_374247e13f7656", campaign.getString("itemNumber__c")); // 项目编号
            formObject.put("fd_3c723b8cda2d12", getOptionStr(campaign.getJSONArray("marketingActivity__c"))); // 是否为市场活动
            formObject.put("fd_3c723bcba60bcc", getOptionStr(campaign.getJSONArray("activityNature__c"))); // 市场活动性质
            formObject.put("fd_374247e32a731a", campaign.getString("projectRequirements__c")); // 项目需求
            formObject.put("fd_374247e690eb20", campaign.getString("projectApprovalContent__c")); // 立项内容
            formObject.put("fd_374247e57a32c6", campaign.getString("effectsBenefits__c")); // 预期效果与收益
            formObject.put("fd_374247e47ec4c0", campaign.getString("projectPlan__c")); // 项目计划
            formObject.put("fd_3c723c77f654e4", campaign.getString("numberOfCustomers__c")); // 潜在客户数
            formObject.put("fd_3c723cc46eb9d2", campaign.getString("businessOpportunities__c")); // 有效商机数
            formObject.put("fd_3c723ce6129488", campaign.getString("orderAmount__c")); // 成单金额
            formObject.put("fd_37424542002b18", getOptionStr(campaign.getJSONArray("budgetFiling__c"))); // 是否有预算备案
            formObject.put("fd_3c2de0c439d6ca", getOptionStr(campaign.getJSONArray("exceedingBudget__c"))); // 是否超出预算
            formObject.put("fd_374247cdce2230", campaign.getString("total__c")); // 总计
            formObject.put("fd_3c3802d62673d4", getOaAccount(campaign, 1)); // 加签

            // 明细数据
            if (budgetDetailsList.size() > 0) {
                JSONArray budgetDetailsArr = new JSONArray();
                for (JSONObject budgetDetail : budgetDetailsList) {
                    JSONObject budgetDetailObj = new JSONObject();
                    budgetDetailObj.put("fd_374247893b5932.fd_374247b0f16c64", budgetDetail.getString("expenseAccount__c")); // 费用科目
                    budgetDetailObj.put("fd_374247893b5932.fd_374247b2145854", budgetDetail.getString("costDescription__c")); // 费用描述
                    budgetDetailObj.put("fd_374247893b5932.fd_374247b457f230", budgetDetail.getString("money__c")); // 金额
                    budgetDetailObj.put("fd_374247893b5932.fd_374247b5b79ef2", budgetDetail.getString("remarks__c")); // 备注
                    budgetDetailsArr.add(budgetDetailObj);
                }
                formObject.put("fd_374247893b5932", budgetDetailsArr);
            }
            logger.info(LOGGER_MSG + "formObject: " + formObject);

            // 获取所有人的OA账号 发送请求
            JSONObject ownerOaAccount = getOaAccount(campaign, 2);
            ResultBody resultBody = pushReqToOa("campaign", campaignName, oaApprovalId, ownerOaAccount, formObject, null);
            logger.info(LOGGER_MSG + "resultBody: " + resultBody);
            if (!Objects.equals(resultBody.getCode(), "200")) {
                logger.error(LOGGER_MSG + "推送市场活动类数据到OA异常: " + resultBody.getMessage());
                return TfReturnMsgTools.getFailResult("推送市场活动类数据到OA异常:" + resultBody.getMessage());
            }

            // 返回的 id 进行保存
            String newOAId = resultBody.getResult().toString();
            Campaign upCampaign = new Campaign();
            upCampaign.setId(campaignId);
            upCampaign.setOaApprovalId__c(newOAId);
            upCampaign.setOaApprovalStatus__c(1);
            upCampaign.setLockStatus(2);
            Boolean update = hcxObjectService.update(upCampaign);
            logger.info(LOGGER_MSG + "update: " + update);

            // 撤回后重新提交需要修改OA的数据状态为 已提交
            if (StringUtils.isNotBlank(oaApprovalId) && (Objects.equals(oaApprovalStatus, "撤回") || Objects.equals(oaApprovalStatus, "驳回"))) {
                resubmitApprovalData(oaApprovalId, ownerOaAccount);
            }

            // 单独的方法更新附件
            JSONArray fileList = campaign.getJSONArray("attachment__c"); // 附件
            UploadOAFile.syncUoloadFile(newOAId, fileKeyMap.get("campaign"), fileList);

            logger.info(LOGGER_MSG + "提交成功");
            return TfReturnMsgTools.getSuccessResult("提交成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(LOGGER_MSG + "处理异常: " + e.getMessage());
            return TfReturnMsgTools.getFailResult("推送异常:" + e.getMessage());
        }
    }


}
